package redis

import (
	"context"
	"log"

	"github.com/go-redis/redis/v8"
	"github.com/nchursin/formtgbot/config"
	"github.com/nchursin/formtgbot/structs"
)

var rdb *redis.Client = nil

func getDb() *redis.Client {
	if nil == rdb {
		rdb = redis.NewClient(&redis.Options{
			Addr:     config.Get().Redis,
			Password: "", // no password set
			DB:       0,  // use default DB
		})
	}
	return rdb
}

func Store(vacancy *structs.Vacancy) {
	getDb().Set(context.TODO(), vacancy.DbKey(), vacancy.ToJson(), 0)
}

func Pop(key string) *structs.Vacancy {
	log.Printf("[redis]: extractting key: %s", key)
	value, err := getDb().Get(context.TODO(), key).Bytes()
	if err != nil {
		panic(err)
	}
	log.Printf("[redis]: extractting key: %s", string(value))
	getDb().Del(context.TODO(), key)
	return structs.NewVacancyFromJson(value)
}
